package com.kern.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kern.api.pojo.Dept;
import com.kern.common.base.ResponseResult;
import com.kern.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 *  提供 restful 服务
 * Created by caoshi at 21:12 2021-09-04
 */
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient client;


    @GetMapping("/dept/get/{id}")
    public Dept getById(@PathVariable("id") String id) {
        return deptService.getDeptById(id);
    }


    // 获取注册到同一注册中心的微服务信息
    @RequestMapping("/dept/discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("services \n " + services);

        List<ServiceInstance> instances = client.getInstances("CONSUMER");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri() + "\t" +
                    instance.getServiceId() + "\t"
            );
        }

        /**
         * 192.168.43.234	8083	http://192.168.43.234:8083	CONSUMER
         *
         */

        return this.client;
    }


    /**
     *  服务提供者暴露接口
     * @param params
     * @return
     */
    @RequestMapping("/dept/givePost")
    public Dept givePost(@RequestBody JSONObject params) {
        System.out.println("params = " + params);

        Dept d = new Dept();
        d.setId("00001");
        d.setDname("consumer-testName");
        d.setDeptno(9);
        d.setDbSource("db1");

        return d;
    }

    /**
     * 服务提供者方
     *  测试远程调用方法
     * @param params
     * @return
     */
    @RequestMapping("/dept/giveRpc")
    public ResponseResult giveRpc(@RequestBody JSONArray params) {
        System.out.println("消费者入参 : params = " + params);

        ResponseResult result = new ResponseResult();
        result.setCode(0);

        // 测试数据
        Dept data = new Dept();
        data.setId("10001");
        data.setDname("测试部门");
        data.setDeptno(101);
        data.setDbSource("测试数据库名称");

        result.setData(data);
        result.setMsg("message");
        result.setEmsg("success");
        return result;
    }





}
